/**
 * Licensed under the Apache License Version 2.0.
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.interknit.knitter.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 */
public class HttpClient
{
	private final String url;

	public HttpClient(String url)
	{
		url = url.trim();
		this.url = url.endsWith("/") ? url : (url + "/");
	}

	public InputStream get() throws IOException
	{
		return get("");
	}

	public InputStream get(String path) throws IOException
	{
		String location = url + (path != null ? path.trim() : "");

		HttpURLConnection connection = (HttpURLConnection) (new URL(location)).openConnection();

		connection.connect();

		return connection.getInputStream();
	}

	public String getString() throws IOException
	{
		return getString("");
	}

	public String getString(String path) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(get(path)));

		StringBuilder sb = new StringBuilder();

		for(; ;)
		{
			String line = br.readLine();
			if(line != null) sb.append(line);
			else break;
		}

		return sb.toString();
	}
}
